package logic

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"mooc_srv/models/mysql"
	"mooc_srv/pkg"
	"strconv"
	"time"

	"mooc_srv/internal/svc"
	"mooc_srv/order"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderCreateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderCreateLogic {
	return &OrderCreateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *OrderCreateLogic) OrderCreate(in *order.OrderCreateRequest) (*order.OrderCreateResponse, error) {
	// todo: add your logic here and delete this line
	userId := 1
	userId = int(in.UserId)
	mooc := mysql.Mooc{}
	err := mooc.MoocView(in.MoocId)
	if err != nil {
		logx.Info("商品不存在")
		return nil, errors.New("商品不存在")
	}
	orderSn := uuid.NewString()
	payTime := time.Now().Format(time.DateTime)
	o := mysql.Order{
		UserId:  int64(userId),
		OrderSn: orderSn,
		PayType: 1,
		PayTime: payTime,
		Amount:  mooc.Price,
	}
	err = o.Create()
	if err != nil {
		logx.Info("创建慕课订单信息失败", err)
		return nil, errors.New("创建慕课订单信息失败")
	}
	totalAmount := strconv.FormatInt(mooc.Price, 10)
	aLiPay := pkg.ALiiPay{
		Subject:     "慕课支付",
		OutTradeNo:  orderSn,
		TotalAmount: totalAmount,
	}
	UrlPay := aLiPay.Pay()
	return &order.OrderCreateResponse{
		UrlPay:  UrlPay,
		OrderId: int64(o.ID),
	}, nil
}
